import { NextResponse } from 'next/server'
import { jwtVerify } from 'jose'

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'your-secret-key')

export async function getUser(request: Request) {
    const authHeader = request.headers.get('Authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }
    
    try {
      const token = authHeader.split(' ')[1]
      const { payload } = await jwtVerify(token, JWT_SECRET)
      return payload.id as string
    } catch (error) {
      return NextResponse.json(
        { error: '无效或过期的token' },
        { status: 401 }
      )
    }
}

// 新增 verifyToken 函数
export async function verifyToken(token: string): Promise<{ userId: string } | null> {
  try {
    const { payload } = await jwtVerify(token, JWT_SECRET)
    return { userId: payload.id as string }
  } catch (error) {
    return null
  }
}

// 从请求中获取用户ID的辅助函数
export async function getUserIdFromRequest(request: Request): Promise<string | null> {
  const authHeader = request.headers.get('Authorization')
  const token = authHeader?.replace('Bearer ', '')
  
  if (!token) {
    return null
  }
  
  const decoded = await verifyToken(token)
  return decoded?.userId || null
}